<template>
  <div class="app-container calendar-list-container">
    <el-row type="flex" class="row-bg" justify="end">
      <el-button type="primary" v-if="sys_permission_add" size="small" icon="el-icon-plus" @click="handlerAddTop">添加
      </el-button>
    </el-row>
    <el-row>
      <el-col :span="8" style='margin-top:15px;'>
        <el-tree
          class="filter-tree"
          node-key="id"
          highlight-current
          :data="treeData"
          :default-expanded-keys="aExpandedKeys"
          :filter-node-method="filterNode"
          :props="defaultProps"
          @node-click="getNodeData"
          @node-expand="nodeExpand"
          @node-collapse="nodeCollapse">
           <span class="custom-tree-node" slot-scope="{ node, data }">
            <el-tooltip class="item" effect="dark" :content="data.code" placement="right">
              <span>{{ node.label }}</span>
            </el-tooltip>
            <span class="tree-node-buttons">
              <el-button type="primary" size="mini" icon="el-icon-plus" circle
                         @click.stop="() => handlerAdd(data)" v-if="sys_permission_add"></el-button>
              <el-button type="primary" size="mini" icon="el-icon-delete" circle
                         @click.stop="() => handleDelete(node, data)" v-if="sys_permission_del"></el-button>
            </span>
          </span>
        </el-tree>
      </el-col>
      <el-col :span="16" style='margin-top:15px;'>
        <el-card class="box-card">
          <el-form :label-position="labelPosition" label-width="80px" :model="form" ref="form">
            <el-form-item label="父权限ID" prop="parentId">
              <el-input v-model="form.parentId" :disabled="true" placeholder="请输入菜单ID"></el-input>
            </el-form-item>
            <el-form-item label="ID" prop="permissionId" v-if="formStatus=='update'">
              <el-input v-model="form.permissionId" :disabled="true" placeholder="请输入ID"></el-input>
            </el-form-item>
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称"></el-input>
            </el-form-item>
            <el-form-item label="描述" prop="description">
              <el-input v-model="form.description" placeholder="请输入描述"></el-input>
            </el-form-item>
            <el-form-item label="编码" prop="code">
              <el-input v-model="form.code" placeholder="请输入编码"></el-input>
            </el-form-item>
            <el-form-item v-if="formStatus == 'create' && sys_permission_edit">
              <el-button type="primary" @click="create">保存</el-button>
            </el-form-item>
            <el-form-item v-else-if="sys_permission_edit">
              <el-button type="primary" @click="update">更新</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>
<script>
  import {fetchTree, getObj, addObj, delObj, putObj} from '@/api/permission'
  import {mapGetters} from 'vuex'

  export default {
    name: 'permission',
    data() {
      return {
        list: null,
        total: null,
        formEdit: true,
        formAdd: true,
        formStatus: '',
        showElement: false,
        typeOptions: ['menu', 'button'],
        appOptions: ['无'],
        methodOptions: ['GET', 'POST', 'PUT', 'DELETE'],
        listQuery: {
          page: 1,
          limit: 100
        },
        treeData: [],
        oExpandedKey: {},
        oTreeNodeChildren: {},
        aExpandedKeys: [],
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        labelPosition: 'right',
        form: {
          permissionId: undefined,
          name: undefined,
          code: undefined,
          parentId: undefined,
          description: undefined
        },
        currentId: 0,
        sys_permission_add: false,
        sys_permission_edit: false,
        sys_permission_del: false
      }
    },
    filters: {
      typeFilter(type) {
        const typeMap = {
          menu: '权限',
          button: '按钮',
          'true': '启用',
          'false': '禁用'
        }
        return typeMap[type] ? typeMap[type] : typeMap[type]
      }
    },
    created() {
      this.getList()
      this.sys_permission_add = this.permissions['sys_permission_add']
      this.sys_permission_edit = this.permissions['sys_permission_edit']
      this.sys_permission_del = this.permissions['sys_permission_del']
    },
    computed: {
      ...mapGetters([
        'elements',
        'permissions'
      ])
    },
    methods: {
      getList() {
        fetchTree().then(response => {
          this.treeData = response.data.data
        })
      },
      filterNode(value, data) {
        if (!value) return true
        return data.label.indexOf(value) !== -1
      },
      nodeExpand(data) {
        let aChildren = data.children
        if (aChildren.length > 0) {
          this.oExpandedKey[data.permissionId] = true
          this.oTreeNodeChildren[data.permissionId] = aChildren
        }
        this.setExpandedKeys()
      },
      nodeCollapse(data) {
        this.oExpandedKey[data.permissionId] = false
        // 如果有子节点
        this.treeRecursion(this.oTreeNodeChildren[data.permissionId], (oNode) => {
          this.oExpandedKey[oNode.permissionId] = false
        });
        this.setExpandedKeys()
      },
      setExpandedKeys() {
        let oTemp = this.oExpandedKey
        this.aExpandedKeys = []
        for (let sKey in oTemp) {
          if (oTemp[sKey]) {
            this.aExpandedKeys.push(parseInt(sKey));
          }
        }
      },
      treeRecursion(aChildren, fnCallback) {
        if (aChildren) {
          for (let i = 0; i < aChildren.length; ++i) {
            let oNode = aChildren[i]
            fnCallback && fnCallback(oNode)
            this.treeRecursion(oNode.children, fnCallback)
          }
        }
      },
      getNodeData(data) {
        if (!this.formEdit) {
          this.formStatus = 'update'
        }
        getObj(data.permissionId).then(response => {
          let data = response.data.data
          this.form = data
        })
        this.currentId = data.permissionId
        this.showElement = true
      },
      handlerEdit() {
        if (this.form.permissionId) {
          this.formEdit = false
          this.formStatus = 'update'
        }
      },
      handlerAddTop() {
        this.currentId = 0
        this.handlerAdd()
      },
      handlerAdd(data) {
        data && (this.currentId = data.permissionId)
        this.resetForm()
        this.formEdit = false
        this.formStatus = 'create'
      },
      handleDelete(data) {
        data && (this.currentId = data.permissionId)
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delObj(this.currentId).then(() => {
            this.getList()
            this.resetForm()
            this.onCancel()
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
        })
      },
      update() {
        putObj(this.form).then(() => {
          this.getList()
          this.$notify({
            title: '成功',
            message: '更新成功',
            type: 'success',
            duration: 2000
          })
        })
      },
      create() {
        addObj(this.form).then(() => {
          this.resetForm()
          this.getList()
          this.$notify({
            title: '成功',
            message: '创建成功',
            type: 'success',
            duration: 2000
          })
        })
      },
      resetForm() {
        this.form = {
          permissionId: undefined,
          name: undefined,
          code: undefined,
          parentId: this.currentId,
          description: undefined
        }
      }
    }
  }
</script>
<style lang="scss" scoped>
  .custom-tree-node {
    flex: 1;
    display: -ms-flexbox;
    display: flex;
    -ms-flex-align: center;
    align-items: center;
    -ms-flex-pack: justify;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }

  .tree-node-buttons {
    display: none;
  }

  .custom-tree-node:hover .tree-node-buttons {
    display: block;
  }
</style>
